#include "crawler.h"
#include "HttpProcess.h"
#include <sstream>
#include <iostream>
#include "convert.h"
#include "url58com.h"
#include "goaway.h"

extern Manager_58com manage58com;
int Crawler_58com::crawl(string from ,string to ,string date)
{
	string c_url = buildUrl(from, to, date);
	if (c_url== "")
	{
		return XX_BUILD_URL_ERR;
	}
	//ConvertGBKToUtf8(c_url);
	HttpProcess http;
	if (http.getResponse(c_url))
	{
		this->content = http.content;
		this->url = c_url;
	}
	return XX_OK;
}


string Crawler_58com::buildUrl(string from ,string to ,string date)
{
	//TODO
	string c_url ="";
	c_url = manage58com.urlmap_58com[from];
	if (c_url =="")return url;
	//ConvertGBKToUtf8(c_url);
	c_url +="huochepiao/?StartStation=";//GBKToUtf8("huochepiao/?StartStation=");

	ConvertGBKToUtf8(from);
	c_url += this->dc.URLEncode(from);

	c_url +=GBKToUtf8("&EndStation=");
	ConvertGBKToUtf8(to);
	c_url += this->dc.URLEncode(to);

	c_url +="&starttime=";//GBKToUtf8("&starttime=");
	c_url +=setInterval(date);//GBKToUtf8( setInterval(date));
#ifdef _DEBUG
	cout<<"url:"<<c_url<<endl;
#endif // _DEBUG

	return c_url;
}

string Crawler_58com::setInterval(const string date)
{
	string tmp =date;
	std::stringstream ret;

	int id1 = tmp.find_first_of('-');
	int id2 = tmp.find_last_of('-');

	string  year = tmp.substr(0,id1);
	string month = tmp.substr(id1+1,id2-1);
	string day = tmp.substr(id2+1);
	int iday = Str2T<int>(day);
	if (iday ==1) iday =2;
	month = T2Str<int>(Str2T<int>(month));

	ret <<year<<'-'<<month<<'-'<<iday-1<<'_'<<year<<'-'<<month<<'-'<<iday+1;
	return ret.str();

}